var _config = {};
var CONFIG_KEY = '_BACKGROUND_CONFIG'
var LOG_LEVEL = {
    INFO: 1,
    ERROR: 2
}
function checkLogin() {
    var serverUrl = _config.serverUrl;
    var checkLoginApi = serverUrl + "/api/login/check";
    var deferred = $.Deferred();
    $.get(checkLoginApi, function (rs) {
        deferred[rs.authenticated ? 'resolve' : 'reject']();
    }, 'json').fail(function() {
        deferred.reject();
    });

    return deferred;
}

function config(obj) {
    if(arguments.length == 0) {
        return _config;
    } else {
        for(var key in obj) {
            _config[key] = obj[key];
        }
        localStorage.setItem(CONFIG_KEY, JSON.stringify(_config))
    }
}

var createAdzoneUrl = "http://pub.alimama.com/common/adzone/selfAdzoneCreate.json"
var batchCreateDoing = false
var batchCreateTimeout = 0
function batchCreateAdzone(param, total) {
    if(batchCreateDoing) {
        alert("批量生成PID的任务正在执行，请稍后重试")
        return
    }
    batchCreateDoing = true
    var idx = 1;
    function doCreate() {
        if(idx >= total) {
            batchCreateDoing = false
            return
        }
        createAdzone(param, idx++).done(function() {
            if(!batchCreateDoing) {
                return
            }
            batchCreateTimeout = setTimeout(doCreate, param.interval * 1000)
        }).fail(function() {
            batchCreateAdzoneStop()
        })

    }

    doCreate()
}

function batchCreateAdzoneStop() {
    batchCreateDoing = false
    clearInterval(batchCreateTimeout)
    sendMessage("adzoneCreateMsg", 'PID生成已停止')
}

function createAdzone(param, idx) {
    idx = idx || 1
    var deferred = $.Deferred()
    getCookie(createAdzoneUrl, '_tb_token_').done(function(cookie) {
        if(!cookie) {
            sendMessage("adzoneCreateMsg", '淘宝联盟登录超时，请登录', LOG_LEVEL.ERROR)
            return deferred.reject()
        }
        var data = {
            tag: param.tag,
            gcid: param.gcid,
            siteid: param.siteId,
            selectact: 'add',
            t: new Date().getTime(),
            _tb_token_: cookie.value,
            pvid: param.pvid,
            newadzonename: 'AT_' + new Date().getTime()
        }
        $.post(createAdzoneUrl, data, function(rs) {
            if(rs.ok) {
                var pid = 'mm_' + param.taobaoUnionId + "_" + rs.data.siteId + "_" + rs.data.adzoneId
                savePid(pid).done(function() {
                    //生成成功
                    sendMessage("adzoneCreateMsg", 'PID生成成功：' + pid + "，第" + idx + "个");
                    deferred.resolve()
                }).fail(function() {
                    sendMessage("adzoneCreateMsg", 'PID保存失败：' + pid + "，第" + idx + "个", LOG_LEVEL.ERROR);
                    deferred.reject()
                })

            } else {
                sendMessage("adzoneCreateMsg", "PID生成失败，第" + idx + "个，" + rs.info.message, LOG_LEVEL.ERROR);
                deferred.reject()
            }
        }, 'json').fail(function(rs) {
            sendMessage("adzoneCreateMsg", "PID生成失败，第" + idx + "个，" + JSON.stringify(rs), LOG_LEVEL.ERROR);
            deferred.reject()
        })
    })
    return deferred
}

function sendMessage(type, msg, level) {
    var pre;
    switch (level) {
        case LOG_LEVEL.INFO: pre = "[INFO]"; break;
        case LOG_LEVEL.ERROR: pre = "[ERROR]"; break;
        default: pre = '[INFO]';
    }
    chrome.extension.sendMessage(  {type: type, msg: pre + " " + msg});
}

function savePid(pid) {
    return $.post(_config.serverUrl + "/api/taobaoPid", {value: pid}, function() {

    }, 'json')
}

function getCookie(url, name) {
    var cookie;
    var deferred = $.Deferred();
    chrome.cookies.get({
        url: url,
        name: name
    }, function(_cookies){
        deferred.resolve(_cookies)
    });
    return deferred
}

_config = JSON.parse(localStorage.getItem(CONFIG_KEY)) || {}

// var i = 0;
// setInterval(function () {
//     i++;
//     chrome.extension.sendMessage(  {type: "aaa", value: i}, function(response) {  console.log(response); }  );
// },10)

/**
 * 订单数据抓取
 * */
var orderGrabber = new OrderGrabber();
orderGrabber.init().run()